<template>
	<!--@change="handleChange"-->
	<a-upload v-if="!$attrs.uploadMode" v-bind="$attrs" :custom-request="customRequest" @remove="del">
		<a-button>
			<upload-outlined></upload-outlined>
			上传
		</a-button>
	</a-upload>

	<!--@change="handleChange"-->
	<a-upload-dragger
		v-if="$attrs.uploadMode === 'drag'"
		v-bind="$attrs"
		:multiple="true"
		:custom-request="customRequest"
		@remove="del"
	>
		<p class="ant-upload-drag-icon">
			<inbox-outlined></inbox-outlined>
		</p>
		<p class="ant-upload-text">单击或拖动文件到此区域上传</p>
		<p class="ant-upload-hint"></p>
	</a-upload-dragger>
</template>

<script setup name="uploadIndex">
	import fileApi from '@/api/dev/fileApi'
	import { getCurrentInstance } from 'vue'
	const { proxy } = getCurrentInstance()
	import { Base64 } from 'js-base64'
	import tool from '@/utils/tool'

	const fileList = ref([])
	const emit = defineEmits({ uploadDone: null })

	const props = defineProps({
		isPreview: {
			type: Boolean,
			default: false,
			required: false
		}
	})

	const customRequest = async ({
		action,
		data,
		file,
		filename,
		headers,
		onError,
		onProgress,
		onSuccess,
		withCredentials
	}) => {
		const formData = new FormData()
		// if (data) {
		// 	Object.keys(data).forEach((key) => {
		// 		formData.append(key, data[key])
		// 	})
		// }
		formData.append('file', file)

		// fileApi
		// 	.fileUploadDynamicReturnId(formData)
		// 	.then((res) => {
		// 		emit('uploadDone', res)
		// 		onSuccess({data: res}, file)
		// 	})
		// 	.catch(onError)
		// 	.finally(() => {
		// 	})

		const fileId = await fileApi.fileUploadDynamicReturnId(formData)
		const res = await fileApi.fileDetail({ id: fileId })
		if (props.isPreview) {
			file.url =
				'http://127.0.0.1:8012/onlinePreview?url=' +
				encodeURIComponent(
					Base64.encode(
						'http://localhost:81/api/dev/file/preview?id=' +
							res.id +
							'&token=' +
							tool.data.get('TOKEN') +
							'&fullfilename=' +
							res.name
					)
				) +
				'&watermarkTxt=' +
				encodeURIComponent('小诺文件预览')
		} else {
			file.url = res.downloadPath
		}

		emit('uploadDone', fileId)
		onSuccess({ data: fileId }, file)
	}
	const del = (file) => {
		fileApi.fileDelete([{ id: file.response.data }]).then((res) => {})
	}
	// const handleChange = async ({ file, fileList }) => {
	// 	if (file.status === 'done') {
	// 		console.log(fileList)
	//
	// 		const res = await fileApi.fileDetail({ id: file.response.data })
	// 		// file.url = res.downloadPath
	// 		file.url =
	// 			'http://127.0.0.1:8012/onlinePreview?url=' +
	// 			encodeURIComponent(
	// 				Base64.encode(
	// 					'http://localhost:81/api/dev/file/preview?id=' +
	// 						res.id +
	// 						'&token=' +
	// 						tool.data.get('TOKEN') +
	// 						'&fullfilename=' +
	// 						res.name
	// 				)
	// 			) +
	// 			'&watermarkTxt=' +
	// 			encodeURIComponent('小诺文件预览')
	// 	}
	// }
</script>
